package com.shenmazg6.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shenmazg6.pojo.TbUser;
import com.shenmazg6.service.TbUserService;
import com.shenmazg6.mapper.TbUserMapper;
import com.shenmazg6.utils.ResultResponse;
import com.shenmazg6.utils.TokenUtils;
import com.shenmazg6.vo.LoginInfoVo;
import com.shenmazg6.vo.PageInfoVo;
import com.shenmazg6.vo.TbUserVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
* @author Think
* @description 针对表【tb_user(用户表)】的数据库操作Service实现
* @createDate 2022-12-19 13:53:25
*/
@Service
@Slf4j
public class TbUserServiceImpl extends ServiceImpl<TbUserMapper, TbUser>
    implements TbUserService{

    @Autowired
    RedisTemplate<String, Object> redisTemplate;

    @Value("${site.token.password}")
    private String tokenPassWord;

    @Value("${site.token.timeout}")
    private Integer tokenTimeOUt;

    @Override
    public ResultResponse login(LoginInfoVo loginInfoVo) {

        //-- 判断用户是否存在
        TbUser one = getOne(new QueryWrapper<TbUser>().lambda().eq(TbUser::getUserName, loginInfoVo.getUserName()).last("limit 1"));
        if(one == null) {
            return ResultResponse.FAILED(404, "用户不存在");
        }

        //-- 判断密码是否正确
        boolean checkpw = BCrypt.checkpw(loginInfoVo.getPassWord(), one.getUserPass());
        if(!checkpw) {
            return ResultResponse.FAILED(403, "用户密码不正确");
        }

        //-- 生成token，返回前端
        String token = TokenUtils.token()
                .setKey(tokenPassWord)
                .setExpire(60 * 60 * 24)
                .setClaim("userId", "" + one.getUserId())
                .setClaim("userName", one.getUserName())
                .makeToken();
        redisTemplate.opsForValue().set(token, token, tokenTimeOUt, TimeUnit.MINUTES);


        TbUserVo tbUserVo = new TbUserVo();
        BeanUtils.copyProperties(one, tbUserVo);

        // 添加token
        tbUserVo.setToken(token);

        // 脱敏
        tbUserVo.setUserPass(null);


        return ResultResponse.SUCCESS(tbUserVo);
    }

    @Override
    public ResultResponse listByPage(PageInfoVo pageInfoVo) {

        log.info("测试分页.........");
        return null;
    }
}




